package com.rgst.controller;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rgst.comm.SearchParam;
import com.rgst.dao.entity.Busi;
import com.rgst.dao.entity.ExtFields;
import com.rgst.dao.repository.BusiConfigRepository;
import com.rgst.dao.repository.BusiExtFieldsRepository;
import com.rgst.dao.repository.BusiRepository;
import com.rgst.dto.Result;
import com.rgst.utils.VoUtils;
import com.rgst.vo.BusiVo;

/**
 * Created by tancw on 2019/12/7.
 */
@Controller
@RequestMapping("busi")
public class BusiController {

    @Autowired
    private BusiRepository busiRepository;

    @Autowired
    private BusiConfigRepository busiConfigRepository;

    @Autowired
    private BusiExtFieldsRepository busiExtFieldsRepository;

    @RequestMapping("list")
    public ModelAndView list() {
        ModelAndView view = new ModelAndView();
        view.addObject("deps", busiConfigRepository.findAllByType("dep"));
        view.setViewName("rgst/busi/list");
        return view;
    }

    @ResponseBody
    @RequestMapping("list-data")
    public Page<Busi> listData(SearchParam sp) {
        Pageable pageable = sp.getPageable(new Sort(Sort.Direction.ASC, "orderNo"));
        ExampleMatcher matcher = ExampleMatcher.
                matching()
                .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.startsWith())
                .withMatcher("state", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("dep", ExampleMatcher.GenericPropertyMatchers.contains());
        Page<Busi> busis = busiRepository.findAll(sp.getParam(Busi.class, matcher), pageable);
        return busis;
    }

    @RequestMapping("form")
    public ModelAndView toForm(Long id) {
        ModelAndView view = new ModelAndView();
        Optional<Busi> busi = busiRepository.findById(id);
        view.addObject("info", busi.get());
        view.addObject("deps", busiConfigRepository.findAllByType("dep"));
        view.setViewName("rgst/busi/busi-form");
        return view;
    }

    @RequestMapping("add")
    @ResponseBody
    public Result save(Busi busi) {
        try {
            Assert.notNull(busi.getTitle());
            Assert.notNull(busi.getSdate());
            Assert.notNull(busi.getEdate());
            busi.setCreateTime(new Date());
            busi.setState(1);
            busiRepository.save(busi);
            return Result.success("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增失败");
        }
    }

    @RequestMapping("update")
    @ResponseBody
    public Result update(@Validated BusiVo busi) {
        try {
            Long busiId = busi.getId();
            Assert.notNull(busiId, "busi id cant be null");
            Optional<Busi> orgBusi = busiRepository.findById(busi.getId());
            Assert.isTrue(orgBusi.isPresent());
            Busi oldBusi = orgBusi.get();
            VoUtils.mergeTo(busi, oldBusi, true);
            busiRepository.save(oldBusi);

            List<String> fields = busi.getExtFiles();
            if (!CollectionUtils.isEmpty(fields)) {
                int i = 0;
                for (String title : fields) {
                    if(StringUtils.isBlank(title)){
                        continue;
                    }
                    ++i;
                    ExtFields extFields = new ExtFields();
                    extFields.setBusiId(busi.getId());
                    extFields.setTitle(title);
                    extFields.setRemark(title);
                    extFields.setName("ext" + busiId + i);
                    extFields.setSno("" + i);
                    busiExtFieldsRepository.save(extFields);
                }
            }
            return Result.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
    }
}
